package com.ctos.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ctos.Exception.CustomException;
import com.ctos.common.Result;
import com.ctos.common.SendMessage;
import com.ctos.common.ValidateCodeUtils;
import com.ctos.entity.User;
import com.ctos.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机验证码短信
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user){

        if (StringUtils.isNotEmpty(user.getPhone())){
            //发送验证码并存入redis中
            try {
                redisTemplate.opsForValue().set(user.getPhone(),SendMessage.message(user.getPhone()),2, TimeUnit.MINUTES);
            } catch (Exception e) {
                log.info(e.getMessage());
                throw new CustomException("发送验证码失败");

            }



            return  Result.success("验证码发送成功");
        }

        return Result.error("手机号为空");

    }

    /**
     * 移动端用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    @Transactional
    public Result<User> login(@RequestBody Map<String,String> map, HttpSession session){
        //获取手机号
        String phone = map.get("phone");
        //获取前端验证码
        String code = map.get("code");
        //取出放在redis内的验证码对比
        String redisCode = String.valueOf(redisTemplate.opsForValue().get(phone));


        try {
            if (redisCode!=null&& redisCode.equals(code) ){
            // if (true){
                //删除在redis中的验证码
                redisTemplate.delete(phone);

                //若成功则再判断是否为新用户 新用户则注册
                LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
                userLambdaQueryWrapper.eq(User::getPhone, phone);
                User user = userService.getOne(userLambdaQueryWrapper);
                if (user==null){
                    user = new User();
                    user.setName("新用户" + ValidateCodeUtils.generateValidateCode4String(5));
                    user.setPhone(phone);
                    user.setStatus(1);
                    userService.save(user);
                }
                //不为新用户 登录
                if (user.getStatus()==1){
                    session.setAttribute("user", user.getId());

                    return Result.success(user);
                }

            }
        } catch (Exception e) {
            throw new CustomException("登录错误请重试");
        }
        //失败返回erro

        return Result.error("登录失败");

    }
    @PostMapping("/loginout")
    public Result<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return Result.success("成功退出");
    }

}
